﻿#include "butlerpart.h"

ButlerPart::ButlerPart(QWidget *parent)
    : QWidget(parent)
{
    createTray();
    startReceiver();
}

ButlerPart::~ButlerPart()
{
    stopReceiver();
}

void ButlerPart::createTray()
{
    trayMenu=new QMenu(this);
    trayMenu->addAction(QStringLiteral("退出"),QApplication::quit);

    tray=new QSystemTrayIcon(this);
    tray->setIcon(QIcon(":/finder.ico"));
    tray->setContextMenu(trayMenu);
    tray->setToolTip(QString(SP_NAME) + QString(" ") + SP_VERSION);
    tray->show();
}

void ButlerPart::startReceiver()
{
    receiver=new BaseUdpReceiver(nullptr,MESSAGE_PORT,false);
    connect(receiver,&BaseUdpReceiver::received,
            this,&ButlerPart::onReceived);
    receiver->moveToThread(&recvThread);
    recvThread.start();
}

void ButlerPart::stopReceiver()
{
    recvThread.quit();
    recvThread.wait();
}

/*
void ButlerPart::sendMessageTest()
{
    Intent intent;
    intent.set_category("DEFAULT");
    intent.set_action(1);
    intent.set_extra("NONE");
    std::string payload;
    if(intent.SerializeToString(&payload))
        sendLocalMessage(QString::fromStdString(payload));
}
*/

void ButlerPart::sendLocalMessage(const QString &message)
{
    QByteArray data=message.toUtf8();
    QUdpSocket().writeDatagram(data,
                               QHostAddress::LocalHost,MESSAGE_PORT);
}

void ButlerPart::onReceived(QByteArray data)
{
    std::string payload=data.toStdString();
    Intent intent;
    if(intent.ParseFromString(payload))
    {
        QString category=QString::fromStdString(intent.category());
        int action=intent.action();
        QString extra=QString::fromStdString(intent.extra());
        qDebug() << category << action << extra;
    }
    else
        qDebug() << "Parse ERROR!";
}
